import api from '../request'
import type { ApiResponse } from '@/types/api'
import { useUserStore } from '@/store/user'

// 户型配置接口
export const houseTypeApi = {
  // 获取用户关联的物业公司
  getUserPropertyCompanies: (userId?: number) => {
    const userStore = useUserStore()
    const currentUserId = userId || userStore.userInfo?.id
    if (!currentUserId) {
      return Promise.reject(new Error('用户ID不能为空'))
    }
    return api.get<ApiResponse<any[]>>(`/api/user/property-companies/user/${currentUserId}`)
  },

  // 根据物业公司ID查询户型配置
  getHouseTypesByPropertyCompany: (propertyCompanyId: number) => {
    return api.get<ApiResponse<any[]>>(`/api/region/house-types/property-company/${propertyCompanyId}`)
  },

  // 根据物业公司ID列表查询户型配置
  getHouseTypesByPropertyCompanies: (propertyCompanyIds: number[]) => {
    return api.post<ApiResponse<Record<number, any[]>>>(`/api/region/house-types/property-companies`, propertyCompanyIds)
  },

  // 创建户型配置
  createHouseType: (data: any) => {
    return api.post<ApiResponse<boolean>>('/api/region/house-types', data)
  },

  // 更新户型配置
  updateHouseType: (id: number, data: any) => {
    return api.put<ApiResponse<boolean>>(`/api/region/house-types/${id}`, data)
  },

  // 删除户型配置
  deleteHouseType: (id: number) => {
    return api.delete<ApiResponse<boolean>>(`/api/region/house-types/${id}`)
  },

  // 分页查询户型配置
  getHouseTypePage: (params: any) => {
    return api.get<ApiResponse<any>>('/api/region/house-types/page', { params })
  },

  // 获取户型配置详情
  getHouseTypeById: (id: number) => {
    return api.get<ApiResponse<any>>(`/api/region/house-types/${id}`)
  },

  // 启用/禁用户型配置
  updateHouseTypeStatus: (id: number, status: boolean) => {
    return api.put<ApiResponse<boolean>>(`/api/region/house-types/${id}/status`, { status })
  },

  // 检查户型名称是否已存在
  checkHouseTypeName: (houseTypeName: string, propertyCompanyId: number, excludeId?: number) => {
    const params: any = { houseTypeName, propertyCompanyId }
    if (excludeId) {
      params.excludeId = excludeId
    }
    return api.get<ApiResponse<boolean>>('/api/region/house-types/check-name', { params })
  }
}
